<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class DailyCooperaterStatisticsTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('daily-cooperater-statistics-task')// 配置一个参数
            ->addArgument('date_str', Argument::OPTIONAL, '当天时间')
            ->setDescription('查询前一天充值的数据');
    }

    protected function execute(Input $input, Output $output)
    {
        $dateStr = $input->getArgument('date_str');
        if ($dateStr){
            $dateTime = date('Ymd', strtotime($dateStr));
            $month = date('Ym', strtotime($dateStr));
        }else{
            $dateTime = date('Ymd', time() - 86400);
            $month = date('Ym', time() - 86400);
        }

        // $doneTaskCount = DistributorsSharingStatistics::where('date',$dateTime)->count();
        // //任务已经跑过
        // if ($doneTaskCount > 0){
        //     return 0;
        // }

        $saveData = [];
        $dateTime = date('Ymd', time() - 86400);
        $month = date('Ym', time() - 86400);

        // $videoIdData = Db::name('cooperater')->where(['status' => 1])->field('id, video_id,video_name')->select()->toArray();
        $whereId['is_delete']=0;
        // $whereId['is_copy']=0;
        $videoIdData = Db::name('videos')->where($whereId)->field('id as video_id, name as video_name,is_copy,original_id')->select()->toArray();

        $videoIds = array_column($videoIdData, 'video_id');

        $date = date('Y-m-d', time() - 86400);
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        $where = [
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['video_id', 'in', $videoIds]
        ];
        $payData = Db::name('pay_record')->where($where)->field('video_id, total_fee')->select()->toArray();
        // var_dump($payData);exit;
        $rechargeData = [];
        foreach ($payData as $value) {
            $rechargeData[$value['video_id']][] = $value['total_fee'];
        }

        //自投充值
        $where_per=[
            ['company_id', 'in', config('enum.self_company_id')]
        ];
        $distributor = Db::name('responsibility_person')->where($where_per)->field('id, name, commission_scale, scale, company_id')->select()->toArray();
        $pitcherIds = array_column($distributor, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $whereSelf=[
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['link_id', 'in', $linkIds],
            ['video_id', 'in', $videoIds]
        ];
        $selfPayData = Db::name('pay_record')->where($whereSelf)->field('video_id, total_fee')->select()->toArray();
        // var_dump(Db::name('pay_record')->getlastsql());exit;
        $selfRechargeData = [];
        foreach ($selfPayData as $value1) {
            $selfRechargeData[$value1['video_id']][] = $value1['total_fee'];
        }

        foreach($videoIdData as $k=>$v){
            $rechargePrice = !empty($rechargeData[$v['video_id']]) ? array_sum($rechargeData[$v['video_id']]) : 0;
            $selfRechargePrice = !empty($selfRechargeData[$v['video_id']]) ? array_sum($selfRechargeData[$v['video_id']]) : 0;
            
            $saveData[] = [
                'date' => $dateTime,
                'month' => $month,
                'video_name' => $v['video_name'],
                'video_id' => $v['video_id'],
                'total_price' => round($rechargePrice, 2),
                'self_price' => round($selfRechargePrice, 2),
                'created_at' => time(),
                'is_copy' => $v['is_copy'],
                'original_id' => $v['original_id']
            ];
        }

        //将原始剧和复制剧区分开
        $copyRecharge=[];
        $originalRecharge=[];
        foreach ($saveData as $vS) {
            if($vS['is_copy']==1){//则是复制剧
                $copyRecharge[]=$vS;
            }else{
                $originalRecharge[]=$vS;
            }
        }
        $mergedRecharge = [];
        foreach ($originalRecharge as $original) {
            $mergedRecharge[$original['video_id']] = [
                'date' => $dateTime,
                'month' => $month,
                'video_name' => $original['video_name'],
                'video_id' => $original['video_id'],
                'total_price' => $original['total_price'],
                'self_price' => $original['self_price'],
                'created_at' => time(),
            ];
        }
        //将原始剧和复制剧充值数据合并
        foreach ($copyRecharge as $copy) {
            if (isset($mergedRecharge[$copy['original_id']])) {
                $mergedRecharge[$copy['original_id']]['total_price'] += $copy['total_price'];
                $mergedRecharge[$copy['original_id']]['self_price'] += $copy['self_price'];
            }
            $mergedRecharge[$copy['original_id']]['total_price']=round($mergedRecharge[$copy['original_id']]['total_price'], 2);
            $mergedRecharge[$copy['original_id']]['self_price']=round($mergedRecharge[$copy['original_id']]['self_price'], 2);
        }

        $bool = Db::name('daily_cooperater_statistics')->insertAll($mergedRecharge);
        return $bool;
    }
}
